package utils;

import lombok.extern.slf4j.Slf4j;
import org.testng.Assert;

import java.util.List;
import java.util.Map;

@Slf4j
public class AssertUtils {
    // 递归比较json对象
    private static void deepCompare(String path, Object expected, Object actual) {
        if (expected instanceof Map) {
            Assert.assertTrue(actual instanceof Map, path + " 应该是个对象");
            Map<String, Object> expMap = (Map<String, Object>) expected;
            Map<String, Object> actMap = (Map<String, Object>) actual;

            for (Map.Entry<String, Object> entry : expMap.entrySet()) {
                String key = entry.getKey();
                Assert.assertTrue(actMap.containsKey(key), path + " 缺少字段: " + key);
                // 递归调用deepCompare
                deepCompare(path + "." + key, entry.getValue(), actMap.get(key));
            }
        } else if (expected instanceof List) {
            Assert.assertTrue(actual instanceof List, path + " 应该是个数组");
            List<Object> expList = (List<Object>) expected;
            List<Object> actList = (List<Object>) actual;

            Assert.assertEquals(actList.size(), expList.size(), path + " 数组长度不匹配");
            for (int i = 0; i < expList.size(); i++) {
                // 递归调用deepCompare
                deepCompare(path + "[" + i + "]", expList.get(i), actList.get(i));
            }
        } else {
            Assert.assertEquals(actual, expected, path + " 值不匹配");
        }
    }

    // 执行断言
    public static void performAssertions(String response, Map<String, Object> assertions) {
        // 检查响应是否为空
        if (response == null || response.trim().isEmpty()) {
            log.error("Response is null or empty, 无法进行断言");
            Assert.fail("Response is null or empty, 无法进行断言");
            return;
        }

        try {
            Object responseJson = JsonUtils.toBean(response, Object.class);
            deepCompare("$", assertions, responseJson);
        } catch (AssertionError e) {
            log.error("断言失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("解析响应JSON失败: {}", e.getMessage(), e);
            Assert.fail("Failed to parse response JSON: " + e.getMessage());
        }
    }
}
